<template>
  <div>
    <a-row :gutter="8" v-if="$route.name=='UserList'">
      <a-col :span="5">
        <a-card :bordered="true" title="组织树">
          <a-tree
            ref="orgtree"
            :treeData="orgTree"
            @select="handleClick"
          />
        </a-card>
      </a-col>
      <a-col :span="19">
        <a-card :bordered="true" title="用户信息列表">
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="8">
                <a-col :md="7" :sm="24">
                  <a-form-item label="姓名">
                    <a-input v-model="queryParam.name"/>
                  </a-form-item>
                </a-col>
                <a-col :md="7" :sm="24">
                  <a-form-item label="账号">
                    <a-input v-model="queryParam.accout"/>
                  </a-form-item>
                </a-col>
                <a-col :md="10" :sm="24">
                  <span class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchUser">查询</a-button>
                    <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                    <a-button style="margin-left: 30px" type="primary" @click="openEditModal('', '1')" v-action:add>新增用户</a-button>
                  </span>
                </a-col>
              </a-row>
              <a-row>
                <s-table
                  ref="stable"
                  size="default"
                  :columns="columns"
                  :data="loadData"
                  :alert="false"
                >
                  <span slot="action" slot-scope="text, record">
                    <template>
                      <a @click="openEditModal(record,'2')">编辑</a>
                      <a-divider type="vertical"/>
                      <a @click="handleDel(record)">删除</a>
                      <a-divider type="vertical"/>
                      <a @click="openPsdModal(record)">密码重置</a>
                    </template>
                  </span>
                </s-table>
              </a-row>
            </a-form>
          </div>
        </a-card>
      </a-col>
    </a-row>
    <router-view/>
    <a-modal
      title="操作"
      style="top: 100px;"
      :width="800"
      v-model="psdModalVis"
      @ok="handleOk"
      :confirmLoading="confirmLoading"
    >
      <a-form :form="editForm">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="账号">
          <a-input v-decorator="['accout']" :disabled="true"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码">
          <a-input v-decorator="['password',{rules: [{ required: true, message: '请输入密码' },{ max:10,message:'长度不能超过20个字符'}]}]"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
import STable from '@/components/table/'
import { getUserPage, deluser, getOrgTree, updateuser } from '@/api/admin'
export default {
  name: 'UserList',
  components: {
    STable
  },
  data () {
    return {
      expandedKeys: ['key-01'],
      // 查询参数
      queryParam: { 'deptCode': '1' },
      // 响应式布局
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10, offset: 1 }
      },
      // 表头
      columns: [
        {
          title: '账号',
          dataIndex: 'accout'
        },
        {
          title: '姓名',
          dataIndex: 'name'
        },
        {
          title: '组织机构',
          dataIndex: 'deptName'
        },
        {
          title: '性别',
          dataIndex: 'sex'
          // customRender: function (text) {
          //   if (text === '1') {
          //     return '男'
          //   } else {
          //     return '女'
          //   }
          // }
        },
        {
          title: '操作',
          width: '200px',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getUserPage(Object.assign(parameter, this.queryParam)).then(res => {
          return res.result
        })
      },
      orgTree: [],
      editForm: this.$form.createForm(this),
      psdModalVis: false,
      confirmLoading: false,
      userInfo: {},
      currentNode: 1
    }
  },
  created () {
    // 获取树形组织信息
    getOrgTree({ 'parentTreeId': 'root' }).then(res => {
      this.orgTree = this.handleVal(res.result.data)
    })
  },
  methods: {
    /**
     * 处理后台返回值 替换名字 id=>key label=>title
     */
    handleVal (value) {
      let str = JSON.stringify(value)
      str = str.replace(/id/g, 'key').replace(/label/g, 'title')
      return JSON.parse(str)
    },
    /**
     * 点击树节点刷新人员信息
     */
    handleClick (item, e) {
      this.queryParam = Object.assign(this.queryParam, {
        'deptCode': item[0]
      })
      this.currentNode = item[0]
      this.$refs.stable.refresh(true)
    },
    /**
     * 查询用户信息
     */
    searchUser () {
      this.queryParam = Object.assign(this.queryParam, {
        'deptCode': this.currentNode
      })
      this.$refs.stable.loadData({}, this.queryParam, {})
    },
    /**
     * 打开编辑用户信息
     */
    openEditModal (item, editType) {
      this.$router.push({ name: 'UserEdit', query: { item, editType } })
    },
    /**
     * 密码重置
     */
    openPsdModal (record) {
      this.userInfo.id = record.id
      setTimeout(() => {
        this.editForm.setFieldsValue({
          accout: record.accout,
          password: '123456'
        })
      }, 0)
      this.psdModalVis = true
    },
    /**
     * 修改密码提交
     */
    handleOk () {
      this.editForm.validateFields((err, values) => {
        if (!err) {
          values.id = this.userInfo.id
          return updateuser(
            values
          ).then(
            res => {
              if (res.status === 200) {
                this.$notification['success']({
                  message: '密码重置成功',
                  duration: 2
                })
                this.psdModalVis = false
              } else {
                this.$notification['error']({
                  message: res.message,
                  duration: 4
                })
              }
            }
          ).catch((err) => {
            if (err || err.response || err.response) {
              this.$notification['error']({
                message: err.response.data.message,
                duration: 4
              })
            }
          })
        }
      })
    },
    /**
     * 单条删除用户信息
     */
    handleDel (item) {
      const _this = this
      this.$confirm({
        title: '警告',
        content: `确认要删除 ${item.name} 的信息吗?`,
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          _this.spinning = true
          // 在这里调用删除接口
          return deluser(
            item.id
          ).then(
            res => {
              if (res.status === 200) {
                _this.$refs.stable.refresh(true)
                _this.$notification['success']({
                  message: '删除成功',
                  duration: 2
                })
              } else {
                _this.$notification['error']({
                  message: res.message,
                  duration: 4
                })
              }
            }
          ).catch(() =>
            _this.$notification['error']({
              message: '出现异常，请联系系统管理员',
              duration: 4
            })
          ).finally(() => {
            _this.spinning = false
          })
        },
        onCancel: () => {
          _this.$notification['info']({
            message: '取消删除操作',
            duration: 4
          })
        }
      })
    }
  }
}
</script>
